import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_base/src/config/app_colors.dart';
import 'package:flutter_base/src/config/color_util.dart';

// 假设您的颜色工具类在这里
// import 'package:flutter_base/src/utils/color_util.dart';

/// 自定义双列联动底部弹出选择器
class CustomLinkedPicker extends StatefulWidget {
  /// 标题
  final String title;

  /// 选项数据
  final List<Map<String, dynamic>> options;

  /// 初始选中的父级索引
  final int initialParentIndex;

  /// 初始选中的子级索引
  final int initialChildIndex;

  /// 确认回调 - 返回选中的父级和子级项
  final void Function(Map<String, dynamic> selectedParent, Map<String, dynamic>? selectedChild) onConfirm;

  /// 取消回调
  final VoidCallback? onCancel;

  /// 主题色
  final Color? primaryColor;

  /// 选择器高度
  final double pickerHeight;

  /// 头部高度
  final double headerHeight;

  /// 选项高度
  final double itemHeight;

  const CustomLinkedPicker({
    super.key,
    required this.title,
    required this.options,
    required this.onConfirm,
    this.initialParentIndex = 0,
    this.initialChildIndex = 0,
    this.onCancel,
    this.primaryColor,
    this.pickerHeight = 300,
    this.headerHeight = 50,
    this.itemHeight = 40,
  });

  /// 显示底部选择器
  static Future<void> show({
    required BuildContext context,
    required String title,
    required List<Map<String, dynamic>> options,
    required void Function(Map<String, dynamic> selectedParent, Map<String, dynamic>? selectedChild) onConfirm,
    int initialParentIndex = 0,
    int initialChildIndex = 0,
    VoidCallback? onCancel,
    Color? primaryColor,
  }) {
    // 数据校验
    if (options.isEmpty) {
      debugPrint("Warning: options list is empty for CustomLinkedPicker.");
      return Future.value();
    }

    return showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return CustomLinkedPicker(
          title: title,
          options: options,
          onConfirm: onConfirm,
          initialParentIndex: initialParentIndex,
          initialChildIndex: initialChildIndex,
          onCancel: onCancel,
          primaryColor: primaryColor ?? AppColors.of(context).primaryColor,
        );
      },
    );
  }

  @override
  State<CustomLinkedPicker> createState() => _CustomLinkedPickerState();
}

class _CustomLinkedPickerState extends State<CustomLinkedPicker> {
  // 父级和子级的滚动控制器
  late FixedExtentScrollController _parentScrollController;
  late FixedExtentScrollController _childScrollController;

  // 父级和子级的选中索引
  late int _selectedParentIndex;
  late int _selectedChildIndex;

  // 当前子级选项列表
  late List<Map<String, dynamic>> _currentChildOptions;

  @override
  void initState() {
    super.initState();

    _selectedParentIndex = widget.initialParentIndex;
    _selectedChildIndex = widget.initialChildIndex;

    _parentScrollController = FixedExtentScrollController(initialItem: _selectedParentIndex);
    _childScrollController = FixedExtentScrollController(initialItem: _selectedChildIndex);

    // 初始化子选项列表
    _updateChildOptions(resetChildIndex: false);
  }

  @override
  void dispose() {
    _parentScrollController.dispose();
    _childScrollController.dispose();
    super.dispose();
  }

  /// 根据选中的父级，更新子级选项列表
  void _updateChildOptions({bool resetChildIndex = true}) {
    // 安全地获取 children 列表
    final children = widget.options[_selectedParentIndex]['children'] as List?;

    _currentChildOptions = children?.map((e) => e as Map<String, dynamic>).toList() ?? [];

    if (resetChildIndex) {
      _selectedChildIndex = 0;
      // 如果子列表不为空，则将子滚轮动画到顶部
      if (_currentChildOptions.isNotEmpty && _childScrollController.hasClients) {
        _childScrollController.animateToItem(0, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
      }
    }
  }

  String _getDisplayText(Map<String, dynamic> item) {
    return item['name']?.toString() ?? '';
  }

  @override
  Widget build(BuildContext context) {
    final primaryColor = widget.primaryColor ?? Theme.of(context).primaryColor;

    return Container(
      height: widget.pickerHeight,
      decoration: BoxDecoration(
        color: AppColors.of(context).whiteColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          _buildHeader(primaryColor),
          const Divider(height: 0.5, thickness: 0.5, color: ColorUtils.lineColor),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: _buildPickerBody(primaryColor),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader(Color primaryColor) {
    return SizedBox(
      height: widget.headerHeight,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              widget.onCancel?.call();
            },
            child: const Text('取消', style: TextStyle(fontSize: 16, color: ColorUtils.textColors6)),
          ),
          Text(
            widget.title,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          TextButton(
            onPressed: () {
              final selectedParent = widget.options[_selectedParentIndex];
              final selectedChild = _currentChildOptions.isNotEmpty ? _currentChildOptions[_selectedChildIndex] : null;

              widget.onConfirm(selectedParent, selectedChild);
              Navigator.of(context).pop();
            },
            child: Text(
              '完成',
              style: TextStyle(color: primaryColor, fontSize: 16),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPickerBody(Color primaryColor) {
    return Row(
      children: [
        // 父级选择器
        _buildColumnPicker(
          controller: _parentScrollController,
          options: widget.options,
          selectedIndex: _selectedParentIndex,
          onSelectedItemChanged: (index) {
            setState(() {
              _selectedParentIndex = index;
              // 联动核心：更新子选项并重置索引
              _updateChildOptions();
            });
          },
          primaryColor: primaryColor,
        ),
        // 子级选择器
        _buildColumnPicker(
          controller: _childScrollController,
          options: _currentChildOptions,
          selectedIndex: _selectedChildIndex,
          onSelectedItemChanged: (index) {
            setState(() {
              _selectedChildIndex = index;
            });
          },
          primaryColor: primaryColor,
        ),
      ],
    );
  }

  Widget _buildColumnPicker({
    required FixedExtentScrollController controller,
    required List<Map<String, dynamic>> options,
    required int selectedIndex,
    required ValueChanged<int> onSelectedItemChanged,
    required Color primaryColor,
  }) {
    return Expanded(
      child: ListWheelScrollView.useDelegate(
        controller: controller,
        itemExtent: widget.itemHeight,
        physics: const FixedExtentScrollPhysics(),
        perspective: 0.005,
        diameterRatio: 1.5,
        onSelectedItemChanged: onSelectedItemChanged,
        childDelegate: ListWheelChildBuilderDelegate(
          childCount: options.length,
          builder: (context, index) {
            final isSelected = index == selectedIndex;
            final item = options[index];
            final displayText = _getDisplayText(item);

            return Center(
              child: Text(
                displayText,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: isSelected ? primaryColor : Colors.grey,
                  fontSize: isSelected ? 18 : 16,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
